import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Carousel, Flex, Grid, WingBlank } from "antd-mobile";
import axios from "axios";

//导入导航菜单图片
import Nav1 from "../../assets/images/nav-1.png";
import Nav2 from "../../assets/images/nav-2.png";
import Nav3 from "../../assets/images/nav-3.png";
import Nav4 from "../../assets/images/nav-4.png";

//导入样式文件
import "./index.scss";

//导航菜单数据
const navs = [
  {
    id: 1,
    img: Nav1,
    title: "整租",
    path: "/home/list",
  },
  {
    id: 2,
    img: Nav2,
    title: "合租",
    path: "/home/list",
  },
  {
    id: 3,
    img: Nav3,
    title: "地图找房",
    path: "/home/map",
  },
  {
    id: 4,
    img: Nav4,
    title: "去出租",
    path: "/home/list",
  },
];

export default function Index() {
  const [state, setState] = useState({
    swipers: [], //轮播图数据
    isSwiperLoaded: false,
    groups: [], //租房小组数据
    news: [], //最新资讯
    curCityName: "上海", //当前城市名字
  });
  const navigate = useNavigate();
  useEffect(() => {
    getSwipers();
    getGroups();
    getNews();
    getCityInfo();
  }, []);

  //获取轮播图数据
  async function getSwipers() {
    const res = await axios.get("http://localhost:8080/home/swiper");
    setState({
      swipers: res.data.body,
      isSwiperLoaded: true,
    });
  }

  //获取租房小组数据
  async function getGroups() {
    const {
      data: { body },
    } = await axios.get("http://localhost:8080/home/groups", {
      params: {
        area: "AREA%7C88cff55c-aaa4-e2e0",
      },
    });
    setState((preState) => {
      return {
        ...preState,
        groups: body,
      };
    });
  }

  //获取最新资讯数据
  async function getNews() {
    let { data: res } = await axios.get(
      "http://localhost:8080/home/news?area=AREA%7C88cff55c-aaa4-e2e0"
    );
    // 把获取到的值设置给state
    setState((preState) => {
      return {
        ...preState,
        news: res.body,
      };
    });
  }

  //通过IP定位 获取城市位置信息
  function getCityInfo() {
    var myCity = new window.BMapGL.LocalCity();
    myCity.get(async (res) => {
      const {
        data: { body },
      } = await axios.get(`http://localhost:8080/area/info?name=${res.name}`);
      setState((preState) => {
        return {
          ...preState,
          curCityName: body.label,
        };
      });
    });
  }

  //渲染轮播图结构
  function renderSwipers() {
    return state.swipers.map((item) => (
      <a
        key={item.id}
        href="http://www.alipay.com"
        style={{
          display: "inline-block",
          width: "100%",
          height: 212,
        }}
      >
        <img
          src={`http://localhost:8080${item.imgSrc}`}
          alt=""
          style={{ width: "100%", verticalAlign: "top" }}
        />
      </a>
    ));
  }

  //渲染导航菜单
  function renderNavs() {
    return navs.map((item) => (
      <Flex.Item key={item.id} onClick={() => navigate(item.path)}>
        <img src={item.img} className="img-responsive" alt="" />
        <h2>{item.title}</h2>
      </Flex.Item>
    ));
  }

  //渲染租房小组
  function renderGroups(item) {
    return (
      <Flex className="group-item" justify="around">
        <div className="desc">
          <p className="title">{item.title}</p>
          <span className="info">{item.desc}</span>
        </div>
        <img src={`http://localhost:8080${item.imgSrc}`} alt="" />
      </Flex>
    );
  }

  //渲染最新资讯
  function renderNews() {
    return state.news
      ? state.news.map((item) => (
          <div className="news-item" key={item.id}>
            <div className="imgwrap">
              <img
                className="img"
                src={`http://localhost:8080${item.imgSrc}`}
                alt=""
              />
            </div>
            <Flex className="content" direction="column" justify="between">
              <h3 className="title">{item.title}</h3>
              <Flex className="info" justify="between">
                <span>{item.from}</span>
                <span>{item.date}</span>
              </Flex>
            </Flex>
          </div>
        ))
      : "";
  }

  return (
    <div className="index">
      {/* 轮播图 */}
      <div className="swiper">
        {state.isSwiperLoaded ? (
          <Carousel autoplay infinite autoplayInterval={5000}>
            {renderSwipers()}
          </Carousel>
        ) : (
          ""
        )}
      </div>
      {/* 顶部导航 */}
      <Flex className="search-box">
        {/* 左侧白色区域 */}
        <Flex className="search">
          {/* 位置 */}
          <div className="location" onClick={() => navigate("/citylist")}>
            <span className="name">{state.curCityName}</span>
            <i className="iconfont icon-arrow" />
          </div>

          {/* 搜索表单 */}
          <div className="form" onClick={() => navigate("/search")}>
            <i className="iconfont icon-seach" />
            <span className="text">请输入小区或地址</span>
          </div>
        </Flex>
        {/* 右侧地图图标 */}
        <i className="iconfont icon-map" onClick={() => navigate("/map")} />
      </Flex>
      {/* 导航菜单 */}
      <Flex className="nav">{renderNavs()}</Flex>
      {/* 租房小组 */}
      <div className="group">
        <h3 className="group-title">
          租房小组 <span className="more">更多</span>
        </h3>
        <Grid
          data={state.groups}
          columnNum={2}
          square={false}
          hasLine={false}
          renderItem={(item) => renderGroups(item)}
        />
      </div>
      {/* 最新资讯 */}
      <div className="news">
        <h3 className="group-title">最新资讯</h3>
        <WingBlank size="md">{renderNews()}</WingBlank>
      </div>
    </div>
  );
}
